<?php

namespace App\Http\Controllers\Touch\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\HomeController;

use Validator;
use Auth;
use App\Models\District;
use App\Models\User\Address;
use Illuminate\Validation\Rule;

class AddressController extends HomeController
{

	/**
     * 发送手机验证码验证
     * @param  array  $data [description]
     * @return [type]       [description]
     */
    private function checkAddressValidator(array $data)
    {
        $attribute =  array(
            'name' => '姓名',
            'tel' => '手机号',
            'areaCode' => '地区编码',
            'postalCode' => '邮政编码',
            'addressDetail' => '详细地址',
            'isDefault' => '默认地址',
        );

        $message  = array(
            'required' => ':attribute必须填写',
            'array' => ':attribute格式不正确',
            'regex' => ':attribute格式错误',
            'in' => ':attribute不在规定范围内',
        );
        return Validator::make($data, [
            'name' => 'bail|required',
            'tel' => ['regex:/^(139|138|137|136|135|134|147|150|151|152|157|158|159|178|182|183|184|187|188|130|131|132|155|156|185|186|145|176|133|153|177|173|180|181|189|170|171)\d{8}$/'],
            'addressDetail' => 'bail|required',
            'areaCode' => 'bail|required',
            'postalCode' => 'bail|required',
            'addressDetail' => 'bail|required',
            'isDefault' => ['required',Rule::in(['true','false'])],
        ],$message,$attribute);
    }


	/**
	 * 更新用户地址
	 * @param  Request $request [description]
	 * @return [type]           [description]
	 */
    public function postUpdate(Request $request){
    	$data = $request->all();
    	$validator = $this->checkAddressValidator($data);
        if($validator->fails()){
            $this->ajaxJson(10,$validator->errors()->first());
        }

        //验证省市区数据
       	$district = new District();
       	$area = $district->cacheFindById($data['areaCode']);
        if (!$area) {
            $this->ajaxJson(10,'未知的地区');
        }
        $city = $district->cacheFindById($area['district_id']);
        $province = $district->cacheFindById($city['district_id']);
       	$user = Auth::user();
       	if(isset($data['id']) && $data['id']>0){
       		$address = $this->_get_one($data['id'],$user);
       	}else{
       		$address = new Address();
       		$address->user_id = $user->id;
       	}
		$address->province  = $province->id;
		$address->city      = $city->id;
		$address->area      = $area->id;
		$address->district  = $data['addressDetail'];
		$address->userName  = $data['name'];
		$address->phone     = $data['tel'];
        $address->postalCode = $data['postalCode'];
		$address->isDefault = $data['isDefault']=='true' ? 1 : 0 ;
		$address->save();

		//更新用户默认地址
		if($data['isDefault']=='true'){
			Address::where('id','!=',$address->id)->where(['user_id'=>$user->id,'isDefault'=>1])->update(['isDefault'=>0]);	
		}
		$this->ajaxJson(0,'更新成功');
    }

    /**
     * 删除用户的一个地址
     * @return [type] [description]
     */
    public function delOne(Request $request){
    	$address = Address::find($request->input('id'));
    	$address->delete();
    	$this->ajaxJson(0,'删除成功');
    }

    /**
     * 获取用户地址列表
     * @return [type] [description]
     */
    public function getList(Request $request){
    	$addresss = Auth::user()->address()->orderBy('isDefault','desc')->orderBy('updated_at','desc')->get();
    	$district = new District();
    	foreach ($addresss as $address) {
            $address->name = $address->userName;
            $address->tel = preg_replace('/(1[0-9]{2})[0-9]{4}([0-9]{4})/i','$1****$2',$address->phone);
    		$address->address = $district->cacheFindById($address->province)->name.$district->cacheFindById($address->city)->name.$district->cacheFindById($address->area)->name.$address->district;
            unset($address->userName,$address->province,$address->city,$address->area,$address->district,$address->phone);
    	}
    	$this->ajaxJson(0,'',$addresss);
    }

    /**
     * 获取所有地区数据
     * @return [type] [description]
     */
    public function getAllDistrict(){
        $district = new District();
        $this->ajaxJson(0,'',$district->getAllDistrictEqual());
    }

    /**
     * 获取单个数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getOne($id){
        $district = new District();
    	$address = $this->_get_one($id,Auth::user());
        $address->tel = $address->phone;
        $address->name = $address->userName;
        $address->province = $district->cacheFindById($address->province)->name;
        $address->city = $district->cacheFindById($address->city)->name;
        $address->county = $district->cacheFindById($address->area)->name;
        $address->addressDetail = $address->district;
        $address->areaCode = $address->area;
        $address->postalCode = $address->postalCode;
        $address->isDefault = $address->isDefault ? true : false;
        unset($address->phone,$address->userName,$address->area,$address->district);
    	$this->ajaxJson(0,'',$address->toArray());	
    }

    /**
     * 公共获取单个数据
     * @return [type] [description]
     */
    private function _get_one($id,$user){
    	$address = Address::find($id);
   		if($address->user_id != $user->id){
   			Log::error("用户[".$user->id.']对不属于他的地址['.$address->id.']进行了非法的操作');
   			$this->ajaxJson(10,'更新失败,请刷新页面');
   		}
   		return $address;
    }


}
